import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
// 导航进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '../store'
import cookie from 'js-cookie'

Vue.use(VueRouter)

const router = new VueRouter({
  routes
})

// 路由前置守卫
router.beforeEach((to, form, next) => {
  NProgress.start()

  // 只要不是登录页，一律判断是否有token, 没有则跳转登录页重新登录
  if (to.path === '/login') {
    next()
  } else if (store.state.token) {
    next()
  } else if (cookie.get('adminToken')) {
    store.commit('setToken', cookie.get('adminToken'))
    next()
  } else {
    next({
      path: '/login',
      query: { redirect: to.fullPath },
      replace: true
    })
  }

  if (to.matched.some(r => r.meta.title)) {
    document.title = `${to.meta.title}`
    next()
  }
})

// 路由后置守卫
router.afterEach(() => {
  NProgress.done()
})

// 处理push报错
// vue warn: Avoided redundant navigation to current location: "/xxx"
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

export default router
